const app = getApp()
const parse = require('mini-html-parser2')
Page({
    data: {

        loginShow:false,
        config: app.config,

        // 当前轮播图索引
        current:0,
        // 租赁说明相关
        other:{
            icon:[
                {title:'租赁说明',icon:'icon-shouji-copy'},
                {title:'租期计算',icon:'icon-riqi'},
                {title:'租后方案',icon:'icon-duanlashuoming'},
                {title:'售后保障',icon:'icon-pinzhibaozhang'},
            ],
            index:0,
            img:[
                '../../../image/other/other1.png',
                '../../../image/other/other2.png',
                '../../../image/other/other3.png',
                '../../../image/other/other4.png'
            ]
        },
        // 商品详情相关
        detail:{
            tabs: [
                { title: '商品详情', subTitle: '爆款好物' },
                { title: '问题说明', subTitle: '摄影航拍' },
                // { title: '常见问题', subTitle: '品质生活' },
            ],
        },
        activeTab:0,

        // fontIcon
        fontIcon:[
            {title:'首页',color:'#5FADEA',tab:'switchTabHome',width:'width:36rpx',icon:`${app.config.image}/shouye_icon.png`},
            {title:'店铺',color:'#E6A93E',tab:'navigateTo',width:'width:40rpx',icon:`${app.config.image}/dianpu_icon.png`},
        ],
        // 弹窗
        showCentent:false,
        combo:{
            cobIndex:0, // 套餐
            terIndex:0, // 租期
            verIndex:0, // 版本
            colIndex:0, // 颜色
            insIndex:0, // 碎屏
        },
        flowImg: '',
        goodsKnow: '',

        warningRoll: true,
        appName: '',

        integerNum: '00',
        decimalsNum: '00',

        explainSwiper:{
          current: 0,
          list:[
            {conUrl: `${app.config.image}/detail_di_min1.png`,text:'快速了解租机流程'},
            {conUrl: `${app.config.image}/detail_di_min2.png`,text:'平台租凭说明'},
            {conUrl: `${app.config.image}/detail_di_min3.png`,text:'平台租凭说明'},
            {conUrl: `${app.config.image}/detail_di_min4.png`,text:'平台租凭说明'},
          ],
        },

        systemSta: 1,

        // 商品详情图片
        detailImgArr: [],

        selectNum: 1,
        unfoldSta: false,
        unfoldStaTwo: false,

        comePath: '',
		disabledSmash: false
    },
    onLoad(query) {

        

        // my.setNavigationBar({
        //   backgroundColor: '#1677FF'
        // });

        if(query.comePath){
          this.setData({
            comePath: query.comePath,
          });
        }

        console.log(565656,query)

        this.getSystem();

        query.param = JSON.parse(query.param)
        this.data.pageId = query.param;
        this.setData({
            query: query,//{id:商品id}
        });

        //携带参数进入商品
        if (query.flowState && query.promotionAccount) {
            app.globalData.flowState = query.flowState
            app.globalData.promotionAccount = query.promotionAccount
        }
        this.getdetail(query.param)
        app._init_(this)
        this.setImgFun();

        if(query.goFun == "clickBtn"){
          this.onPopupOpen();
        }
    },
    onShareAppMessage() {
      let id = this.data.pageId;
      return {
        title: this.data.config.appName,
        desc: '分享商品',
        path: 'pages/product/detail/detail?param=' + id
      }
    },

    getSystem(){
      let systemInfo = my.getSystemInfoSync();
      let sta = 1;
      if(systemInfo.platform === "android"){
        sta = 1;
      }else{
        sta = 2;
      }
      this.setData({
        systemSta: sta,
      })
    },

    setImgFun(){
      let nam = this.data.config.thisName;
      let urlHead = this.data.config.image
      if(nam === 1){
        this.setData({
          flowImg: urlHead + 'p_flow.png',
          goodsKnow: urlHead+ 'p_goods_know.png'
        })
      }else if(nam === 2){
        this.setData({
          flowImg: urlHead + 'p_flow.png',
          goodsKnow: urlHead+ 'p_goods_know.png'
        })
      }
    },

    // 
    unfoldStaFun(){
      this.setData({
        unfoldSta: true
      })
    },

    unfoldStaFunTwo(){
      this.setData({
        unfoldStaTwo: true
      })
    },



    // api
    // 获取商品详情
    getdetail(id){
        app.product.detail(id)
        .then(json=>{
            console.log("==============商品数据============", json)
                json.data.category = JSON.parse(json.data.category)
                json.data.colors = JSON.parse(json.data.colors)
                json.data.match = JSON.parse(json.data.match)
                json.data.params = JSON.parse(json.data.params)

                console.log(123,json.data)

                json.data.params.sort((a, b) => {
                    if (a.name == '租完归还') {
                        return 1
                    } else {
                        return -1
                    }
                })
				let term_value = json.data.params[0].term_list[0].value
                let combo = this.data.combo
				if (term_value == 30 || term_value == 14 || term_value == 24) {
					console.log('现在是什么', term_value)
					combo.insIndex = json.data.smash
					this.setData({
						disabledSmash: true
					})
				}
				combo.insIndex = json.data.smash
				this.setData({
					disabledSmash: true
				})
                combo.cobIndex = json.data.params.length-1
                this.setData({
                    combo
                })
				
                console.log(8989,combo)
                json.data.slideshows = JSON.parse(json.data.slideshows)
                json.data.msg = `${json.data.tit}`
                json.data.image = json.data.slideshows[0]
                //   json.data.content = parse(json.data.content)
                // let favorite = json.data.favorite
                // 富文本转化nodes节点
                let html = json.data.content

                // 只保留图片
                let data = [];
                html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, function (match, capture) {
                  data.push(capture);
                });
                // let abrasionImgArr = [
                //    `${this.data.config.image}/mosun.png`,
                //   `${this.data.config.image}/mosun_con.png`,
                //   `${this.data.config.image}/peichang.png`,
                //   `${this.data.config.image}/peichang_con.png`
                // ];
                // data.push(...abrasionImgArr);
                
                this.setData({ 
                  detailImgArr: data
                });

                // html = html.replace(/<img>*/gi, '</img><img width="100%!important" style="display:block;" ')
                // html = html.replace(/<br\/>*/gi, '<br></br>')
                // html = html.replace(/<\/?picture>*/gi, '')
                // console.log(666,html)
                // parse(html, (err, nodes) => {
                //     if (!err) {
                //         this.nodesChange(nodes)
                //         this.setData({ nodes });
                //     }
                // });
                // console.log("==============商品数据============", json)

                // this.setData({ favorite });
                this.setData({ data: json.data });
                let params = { tit: "" }
                params.tit = json.data.params
                this.setData({ params: params });

                let allNum = (params.tit[combo.cobIndex].term_list[combo.terIndex].specifications[combo.verIndex].money / (params.tit[combo.cobIndex].term_list[combo.terIndex].value*100)).toFixed(2);
				let zvalue = params.tit[combo.cobIndex].term_list[combo.terIndex].value
				if (zvalue == 14 || zvalue == 24) {
					allNum = (params.tit[combo.cobIndex].term_list[combo.terIndex].specifications[combo.verIndex].money / (params.tit[combo.cobIndex].term_list[combo.terIndex].value *100)).toFixed(2)
				}
                let integerNum = allNum.split('.')[0];
                let decimalsNum = allNum.split('.')[1];


                this.setData({
                  integerNum: integerNum,
                  decimalsNum: decimalsNum
                })
                
        })
        .catch((err)=>{
            if (err.code == 102) {
                my.alert({
                    title: '亲',
                    content: '该商品已下架',
                    buttonText: '我知道了',
                    success: () => {
                        my.navigateBack();
                    }
                });
                return
            }
        })
    },
    nodesChange(nodes) {
        if (!nodes) {
            return
        };
        nodes.forEach(item => {
            if (item.name == "img") {
                item.children = []
            } else {
                this.nodesChange(item.children)
            }
        });
    },
    callBackFn(value) {
      console.log(value);
      let num = 1;
      if (value) {
        num = value
      }
      this.setData({
        selectNum: num
      })
    },
    getshopinfo(sid){
        let timestamp = new Date().getTime()
        app.product.shops(sid)
        .then(res=>{
            // console.log("====shop-info=======>>>>>>>>>>",res)
                let cloudService = res.data.cloudService
                if (cloudService == null) {
                    return
                }
                this.setData({
                    cloudService: cloudService
                })
                // console.log(res)
        })
    },


    // login
    getUser(){
        // console.log("1111111111111111111")
        let user = my.getStorageSync({ key: 'user' });
        // console.log("user", user)
        // 判断有没有登录
        if (!user.data) {
            // console.log("1111111111111111111")
            this.setData({
                loginShow: true,
            })
            return true
        }
    },
    login(){
        this.setData({
            loginShow:true
        })
    },

    onLgin(data){
        this.setData(data)
    },

    // 确定
    // 商品数据传参
    onSubmit() {

         if(this.getUser()){
            return false
        }
        let {cobIndex,terIndex,verIndex,colIndex,insIndex} = this.data.combo

        let stock = this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].stock
        // console.log(stock)
        // if (!parseInt(stock)) {
        //     my.alert({
        //         content: '该商品缺货中'
        //     });
        //     return false
        // }
        // console.log(cobIndex,terIndex,verIndex,colIndex,insIndex)

        let obj = {
          msg: this.data.data.msg,  // 商品名
          id: this.data.data.id,  // 商品id
          sid: this.data.data.sid,
          skuId: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].skuId,
          version: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].version,
          detail: `${this.data.params.tit[cobIndex].name} ${this.data.data.colors[colIndex].tit} ${this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].tit}`,   // 套餐
          trem: this.data.params.tit[cobIndex].term_list[terIndex].name, // 租期
          trem_value: this.data.params.tit[cobIndex].term_list[terIndex].value, // 租期
          slideshows: this.data.data.slideshows,

          neicun: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].tit,//内存
          cash: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].cash,//押金
          money: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].money,//金额
          buyOut: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].buyout, // 完结价
          purchase: this.data.params.tit[cobIndex].term_list[terIndex].specifications[verIndex].purchase, // 采购价

          wangluo: this.data.data.category.wangluo,  //网络
          color: this.data.data.colors[colIndex],  // 颜色
          type: this.data.data.type, // 成色 0为新，1为二手
          match: { tit: this.data.data.match, value: this.data.match },  // 可选搭配
          smash: { tit: this.data.data.smash, value: insIndex },  //碎屏保障
          freight: this.data.freight ? '到付' : "包邮",
          saleQuantity: this.data.selectNum,

          shops: this.data.data.shops,

          promotionType: this.data.data.promotionType
        }
        if(this.data.comePath == "ticket"){
          obj.clipCoupons = 1
        }
        if(this.data.comePath == "testGoods"){
          obj.testOrder = 2
        }else{
          obj.testOrder = 1
        }
        const data = JSON.stringify(obj);
        console.log('tiaozhuan',obj)
        my.navigateTo({
            url: "/pages/product/confirm/confirm?data=".concat(encodeURIComponent(data))
        });
    },

    // swiperChange
    swiperChange(e){
        const current = e.detail.current
        this.setData({current})
    },

    // other
    otherClick(e) {
        let other = this.data.other
        other.index = e.target.dataset.index
        this.setData({other})
    },

    // tabs
    handleTabClick({ index, tabsName }){
        this.setData({
            [tabsName]: index,
        });
    },

    // popup
    onPopupOpen(){
        let combo = this.data.combo;
        combo.cobIndex = 0;
        this.setData({showCentent: true,combo:combo});
    },
    onPopupClose(){
        this.setData({showCentent: false});
    },
    comSelect(e){
        let {key,value} = e.target.dataset.item,
        combo = this.data.combo;
        if(key == 'insIndex') {
            if(combo.insIndex!=0) {
                combo[key] = 0
            }else {
                combo[key] = value
            }
        }else if (key == 'terIndex') {
			console.log(this.data.params)
			let val = this.data.params.tit[this.data.combo.cobIndex].term_list[value]
			if (val == 30 || val == 14 || val == 24) {
				this.setData({
					disabledSmash: true
				})
			}
			// console.log(this.data.params.tit[this.data.combo.cobIndex].term_list[value])
            combo[key] = value
        }else  {
            combo[key] = value
        }
        this.setData({
           combo
        })
    },
    // 跳转
    navigateTo(e){
        app.navigateTo(e)
    },

    // 首页
    switchTabHome(){
        my.switchTab({
            url:"/pages/main/home/home"
        })
    },
    // 客服
    server(){
        my.showToast({
            content:'暂未开启'
        });
    },


    closeWarning(){
      this.setData({
        warningRoll: false
      })
    }







});
